package networking;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;

/**
 * function   TCP服务端实现
 * Created by lhlong on 2017/1/6.
 */
public class TcpConnectionThread implements Runnable
{
    private Socket client;

    public TcpConnectionThread(Socket client){
        this.client = client;
    }
    public void run() {
        try {
            PrintStream psout = new PrintStream(client.getOutputStream());
            BufferedReader buf = new BufferedReader(new InputStreamReader(client.getInputStream()));
            boolean flag =true;
            while(flag){
                //接收从客户端发送过来的数据
                String str =  buf.readLine();
                if(str == null || "".equals(str)){
                    flag = false;
                }else{
                    if("bye".equals(str)){
                        flag = false;
                    }else{
                        //将接收到的字符串前面加上echo，发送到对应的客户端
                        psout.println("echo:" + str);
                    }
                }
            }
            psout.close();
            client.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
